---
import Post from '~/components/Post.astro'
import LayoutDefault from '~/layouts/LayoutDefault.astro'
import { getPosts } from '~/utils'
import type { InferGetStaticPropsType, GetStaticPaths } from 'astro'
import Pagination from '~/components/Pagination.astro'
import Comments from '~/components/Comments.astro'

export const getStaticPaths = (async ({}) => {
  const posts = await getPosts()
  return posts.map((post, idx) => {
    const prev = posts[idx - 1]
    const next = posts[idx + 1]
    return {
      params: { slug: post.slug },
      props: { entry: post, next, prev },
    }
  })
}) satisfies GetStaticPaths

// type Params = InferGetStaticParamsType<typeof getStaticPaths>
type Props = InferGetStaticPropsType<typeof getStaticPaths>

const { entry, prev, next } = Astro.props
const { Content } = await entry.render()
const { translate: t } = Astro.locals

function getUrl(slug: string) {
  return `/posts/${slug}`
}
---

<LayoutDefault title={entry.data.title} desc={entry.data.description} banner={entry.data.banner}>
  <Post post={entry}>
    <Content />
  </Post>
  <Pagination
    showLeft={Boolean(prev)}
    leftTitle={`${t('prev_post')}: ${prev?.data.title}`}
    leftUrl={getUrl(prev?.slug)}
    showRight={Boolean(next)}
    rightTitle={`${t('next_post')}: ${next?.data.title}`}
    rightUrl={getUrl(next?.slug)}
    showPageCount={false}
  />
  <!-- BUG 这里使用 client:visible 会导致构建失败。ref: https://github.com/withastro/astro/issues/7329 -->
    <Comments post={entry} />
</LayoutDefault>

<script>
  import '@github/clipboard-copy-element'

  document.addEventListener('clipboard-copy', function (event) {
    const target = event.target as HTMLElement
    const icon = target.querySelector('.icon') as HTMLElement
    icon.classList.replace('i-mdi-content-copy', 'i-mdi-check')
    setTimeout(() => {
      icon.classList.replace('i-mdi-check', 'i-mdi-content-copy')
    }, 1500)
  })

  const codeBlocks = Array.from(document.querySelectorAll('pre'))
  const icon = "<div class='i-mdi-content-copy icon text-white'></div>"
  for (let codeBlock of codeBlocks) {
    let wrapper = document.createElement('div')
    wrapper.className = 'code-container'

    let copyButton = document.createElement('clipboard-copy')
    let code = codeBlock.querySelector('code')
    copyButton.value = code?.innerText ?? ''
    copyButton.className = 'clipboard-copy'
    copyButton.innerHTML = icon

    codeBlock.appendChild(copyButton)

    codeBlock.parentNode?.insertBefore(wrapper, codeBlock)
    wrapper.appendChild(codeBlock)
  }
</script>

<style is:global>
  .code-container {
    position: relative;
  }
  .clipboard-copy {
    position: absolute;
    top: .5rem;
    right: .5rem;
    width: 1.75rem;
    height: 1.75rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.25rem;
  }

  .clipboard-copy:hover {
    background-color: #30363d;
  }
</style>
